package com.miniprogram.common.utils;

import com.miniprogram.bean.dto.DistanceDto;
import org.gavaghan.geodesy.Ellipsoid;
import org.gavaghan.geodesy.GeodeticCalculator;
import org.gavaghan.geodesy.GeodeticCurve;
import org.gavaghan.geodesy.GlobalCoordinates;

public class CalculateDistanceUtils {
//    public static void main(String[] args)
//    {
//        GlobalCoordinates source = new GlobalCoordinates(29.490295, 106.486654);
//        GlobalCoordinates target = new GlobalCoordinates(29.615467, 106.581515);
//
//        double meter1 = getDistanceMeter(source, target, Ellipsoid.Sphere);
//        double meter2 = getDistanceMeter(source, target, Ellipsoid.WGS84);
//
//        System.out.println("Sphere坐标系计算结果："+meter1 + "米");
//        System.out.println("WGS84坐标系计算结果："+meter2 + "米");
//    }

    private static double getDistanceMeter(GlobalCoordinates gpsFrom, GlobalCoordinates gpsTo, Ellipsoid ellipsoid) {
        GeodeticCurve geoCurve = new GeodeticCalculator().calculateGeodeticCurve(ellipsoid, gpsFrom, gpsTo);
        return geoCurve.getEllipsoidalDistance();
    }

    /**
     * 计算两地距离
     *
     * @param sourceLongitude 源地的经度
     * @param sourceLatitude  源地的纬度
     * @param targetLongitude 目标地的经度
     * @param targetLatitude  目标地的纬度
     * @return double距离
     */
    private static double getDistanceMeter(double sourceLongitude, double sourceLatitude, double targetLongitude, double targetLatitude, Ellipsoid ellipsoid) {
        GlobalCoordinates source = new GlobalCoordinates(sourceLongitude, sourceLatitude);
        GlobalCoordinates target = new GlobalCoordinates(targetLongitude, targetLatitude);
        return getDistanceMeter(source, target, ellipsoid);
    }

    public static DistanceDto getDistanceForDto(double sourceLongitude, double sourceLatitude, double targetLongitude, double targetLatitude) {
        DistanceDto dto = new DistanceDto();
        double meter = getDistanceMeter(sourceLongitude, sourceLatitude, targetLongitude, targetLatitude, Ellipsoid.Sphere);
        dto.setDistance(meter);
        dto.setDistanceStr(formatDistance(meter));
        return dto;
    }

    /**
     * 计算两地距离并整理
     *
     * @param sourceLongitude 源地的经度
     * @param sourceLatitude  源地的纬度
     * @param targetLongitude 目标地的经度
     * @param targetLatitude  目标地的纬度
     * @return str距离
     */
    public static String getDistanceMeterWithFormat(double sourceLongitude, double sourceLatitude, double targetLongitude, double targetLatitude) {
        double meter = getDistanceMeter(sourceLongitude, sourceLatitude, targetLongitude, targetLatitude, Ellipsoid.Sphere);
        return formatDistance(meter);
    }

    private static String formatDistance(double meter) {
        if (meter < 1000) {
            return "小于1公里";
        }
        double quotient = meter / 1000;
        if (quotient < 1000) {
            return "约" + (int) Math.ceil(quotient) + "公里";
        } else {
            return "大于1千公里";
        }
    }

}